package com.jboa.util;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jboa.model.Employee;



public class AuthenticationFilter implements Filter {

	private static Log log = LogFactory.getLog(AuthenticationFilter.class);

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		String path = req.getServletPath();
		
		if (path.endsWith("/login.action") || path.endsWith("/login.jsp")||path.endsWith("/random1.action")
				|| path.endsWith(".css")
				|| path.endsWith(".gif")|| path.endsWith(".jpg") || path.endsWith(".png")
				|| path.endsWith(".js") || path.endsWith("/index.jsp")) {
			chain.doFilter(request, response);
		} else {			
			Employee user = (Employee) session.getAttribute("curruser");
			if (user == null) {
				log.debug("User doesn't exist in session");				
				res.sendRedirect(req.getContextPath() + "/login.jsp");
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void destroy() {
	}
}